package com.guqj.thread;

/**
 * <p>
 * 一个可能的（和常见的）使用是当你有一些对象不是线程安全的，但你想避免同步访问该对象（例如，SimpleDateFormat）。<br>
 * 相反，给每个线程自己的对象实例
 * </p>
 * 
 * @author guqj
 * @date 2017年3月16日
 */
public class ThreadLocalTest {

	public static void main(String[] args) {
		ThreadLocalMain localMain = new ThreadLocalMain();
		for (int i = 0; i < 10; i++) {
			new ThreadLocalMainClient(localMain).start();
		}
	}
}

class ThreadLocalMain {
	private static ThreadLocal<Integer> local = new ThreadLocal<Integer>() {
		public Integer initialValue() {
			return 0;
		}
	};

	public Integer getNext() {
		local.set(local.get() + 1);
		return local.get();
	}
}

class ThreadLocalMainClient extends Thread {

	private ThreadLocalMain localMain;

	public ThreadLocalMainClient(ThreadLocalMain localMain) {
		this.localMain = localMain;
	}

	@Override
	public void run() {
		for (int i = 0; i < 3; i++) {
			System.out.println("当前线程:[" + Thread.currentThread().getName() + "]---> num: " + localMain.getNext());
		}
	}
}